// eslint-disable-next-line
import { BasicLayout } from '@/layouts'
import DemoRouter from './module/demo.config'
import AccountRouter from './module/account.config'
import request from '@/core/request'
// 前端未找到页面路由（固定不用改）
const NotFoundRouter = {
  path: '*',
  redirect: '/404',
  hidden: true
}

// 根级菜单
const RootRouter = {
  name: 'index',
  path: '/',
  component: BasicLayout,
  redirect: '/home',
  meta: {
    title: '首页'
  },
  children: []
}

const HomeRouter = {
  path: '/home',
  name: 'home',
  hidden: true,
  component: () => import('@/views/Home'),
  meta: { title: '首页', keepAlive: false }
}

const handleMenus = (menus, arr) => {
  if (menus && menus.length > 0) {
    return menus.map((item) => {
      const tmpArr = arr.slice()
      tmpArr.push(item.code)
      const menu = {
        path: '/' + tmpArr.join('/'),
        name: tmpArr.join('-'),
        meta: {
          title: item.name,
          icon: item.icon || null,
          keepAlive: true
        },
        hidden: !item.isUse,
        component: item.layer === 1 ? {
          name: 'RouteView',
          render: h => h('router-view')
        } : () => import(`@/views/${tmpArr.join('/')}/Index`)
      }
      if (item.children && item.children.length > 0) {
        menu.children = handleMenus(item.children, tmpArr)
        menu.redirect = menu.children[0].path
      }
      return menu
    })
  }
  return []
}

export const generatorDynamicRouter = () => {
  return new Promise((resolve) => {
    request.get('/zg-system/user/menu', {}, data => {
      const arr = handleMenus(data, [])
      const routers = []
      const childrenNav = [
        HomeRouter,
        AccountRouter,
        ...arr,
        DemoRouter
      ]
      RootRouter.children = childrenNav
      routers.push(RootRouter)
      routers.push(NotFoundRouter)
      resolve(routers)
    })
  })
}
